﻿using MyModule.Breeding;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.ObjectMapping;

namespace MyModule.ManageSheep
{
    public class EliminateService : ApplicationService, IEliminateService
    {
        private readonly IRepository<Eliminate, int> _weighInfoRepository;
        private readonly IRepository<VarietyInfo, int> _varietyInfoRepository;
        private readonly IRepository<Dreproduction, int> _dreproductionRepository;
        private readonly IRepository<EliminateCause, int> _eliminateCauseRepository;
        private readonly IHttpClientFactory _httpClientFactory;

        public EliminateService(IRepository<Eliminate, int> weighInfoRepository, IRepository<VarietyInfo, int> varietyInfoRepository, IRepository<Dreproduction, int> dreproductionRepository, IRepository<EliminateCause, int> eliminateCauseRepository, IHttpClientFactory httpClientFactory)
        {
            _weighInfoRepository = weighInfoRepository;
            _varietyInfoRepository = varietyInfoRepository;
            _dreproductionRepository = dreproductionRepository;
            _eliminateCauseRepository = eliminateCauseRepository;
            _httpClientFactory = httpClientFactory;
        }
        /// <summary>
        /// 添加淘汰信息
        /// </summary>
        /// <param name="eliminateDTO"></param>
        /// <returns></returns>
        public async Task<ResultDto<EliminateDTO>> CreateAsync(EliminateDTO eliminateDTO)
        {
            var list = await _weighInfoRepository.FirstOrDefaultAsync(x => x.Earbugles == eliminateDTO.Earbugles);
            if (list == null)
            {
                Eliminate eliminate = new Eliminate();
                eliminate.Edate = eliminateDTO.Edate;
                eliminate.Earbugles = eliminateDTO.Earbugles;
                eliminate.ECid = eliminateDTO.ECid;
                eliminate.Exit = eliminateDTO.Exit;
                eliminate.Emeasures = eliminateDTO.Emeasures;
                eliminate.Vid = eliminateDTO.Vid;
                eliminate.Esex = eliminateDTO.Esex;
                eliminate.Rid = eliminateDTO.Rid;
                eliminate.Ebuildings = eliminateDTO.Ebuildings;
                eliminate.Ecolumns = eliminateDTO.Ecolumns;
                var result = await _weighInfoRepository.InsertAsync(eliminate);
                var listCount = ObjectMapper.Map<Eliminate, EliminateDTO>(result);
                if (listCount != null)
                {
                    return new ResultDto<EliminateDTO>() { Code = 200, Message = "添加成功" };
                }
                else
                {
                    return new ResultDto<EliminateDTO>() { Code = 500, Message = "添加失败" };
                }
            }
            else
            {
                return new ResultDto<EliminateDTO>() { Code = 501 };
            }
        }


        /// <summary>
        /// 删除淘汰信息
        /// </summary>
        /// <param name="Eid"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task DeleteAsync(int Eid)
        {
            await _weighInfoRepository.DeleteAsync(Eid);
        }
        /// <summary>
        /// 繁殖状态信息
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<List<DreproductionDTO>> GetDreproductionAsync()
        {
            var result = await _dreproductionRepository.GetListAsync();
            return ObjectMapper.Map<List<Dreproduction>, List<DreproductionDTO>>(result);
        }
        /// <summary>
        /// 淘汰原因信息
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<List<EliminateCauseDTO>> GetEliminateCauseAsync()
        {
            var result = await _eliminateCauseRepository.GetListAsync();
            return ObjectMapper.Map<List<EliminateCause>, List<EliminateCauseDTO>>(result);
        }

        /// <summary>
        /// 显示查询全部
        /// </summary>
        /// <param name="Earbugles"></param>
        /// <param name="ECid"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<List<EliminateVarietyDreprDTO>> GetListAppAsync(int ECid, string? Earbugles)
        {
            var result = await _weighInfoRepository.ToListAsync();
            var varietie = await _varietyInfoRepository.ToListAsync();
            var dreproduction = await _dreproductionRepository.ToListAsync();
            var eliminateCause  = await _eliminateCauseRepository.ToListAsync();
            var list = (from a in result
                        join c in varietie on a.Vid equals c.Id
                        join d in dreproduction on a.Rid equals d.Id
                        join e in eliminateCause on a.ECid equals e.Id
                        select new EliminateVarietyDreprDTO
                        {
                            Id = a.Id,
                            Edate  = a.Edate,
                            Earbugles  = a.Earbugles,
                            ECid  = e.Id,
                            Exit   = a.Exit,
                            Emeasures   = a.Emeasures,
                            Vid   = c.Id,
                            Esex   = a.Esex,
                            Rid   = d.Id,
                            Ebuildings   = a.Ebuildings,
                            Ecolumns     = a.Ecolumns,
                            ECname      = e.ECname,
                            Rname       = d.Rname,
                            Vname       = c.Vname
                        }).ToList();
            if (!string.IsNullOrEmpty(Earbugles))
            {
                list = list.Where(x => x.Earbugles == Earbugles).ToList();
            }
            if (ECid != 0)
            {
                list = list.Where(x => x.ECid == ECid).ToList();
            }
            return list.OrderByDescending(x => x.Id).ToList();
        }

        /// <summary>
        /// 查询单个数据
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<EliminateDTO> GetListAsync(int id)
        {
            var result = await _weighInfoRepository.FirstOrDefaultAsync(x => x.Id == id);
            return ObjectMapper.Map<Eliminate, EliminateDTO>(result);
        }

        /// <summary>
        /// 修改淘汰信息
        /// </summary>
        /// <param name="eliminateDTO"></param>
        /// <returns></returns>
        public async Task<ResultDto<EliminateDTO>> UpdateAsync(EliminateDTO eliminateDTO)
        {
                var result = await _weighInfoRepository.FindAsync(eliminateDTO.Id);
                if (result == null)
                {
                    return new ResultDto<EliminateDTO>() { Code = 500 };
                }
                ObjectMapper.Map(eliminateDTO, result);
                var count = await _weighInfoRepository.UpdateAsync(result);
                var listCount = ObjectMapper.Map<Eliminate, EliminateDTO>(count);
                if (listCount != null)
                {
                    return new ResultDto<EliminateDTO>() { Code = 200, Message = "修改成功" };
                }
                else
                {
                    return new ResultDto<EliminateDTO>() { Code = 500, Message = "修改失败" };
                }
        }
        /// <summary>
        /// 种母存栏
        /// </summary>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public async Task<List<BreedingDTO>> GetSheepBreedingCounts()
        {
            var client = _httpClientFactory.CreateClient();
            // 发送 HTTP 请求获取数据
            var response = await client.GetAsync("https://localhost:44336/api/app/growthstage/sheep-showm");

            if (!response.IsSuccessStatusCode)
            {
                throw new Exception("Failed to fetch data from the API.");
            }

            // 读取响应内容并反序列化
            var jsonString = await response.Content.ReadAsStringAsync();
            var data = JsonConvert.DeserializeObject<List<YourDataModel>>(jsonString); 

            // 使用 LINQ 进行分组和计数
            var breedingCounts = data
                .GroupBy(item => item.Reproductivestate)
                .Select(group => new BreedingDTO
                {
                    SumName = group.Key,
                    SumCount = group.Count()
                })
                .ToList();

            return breedingCounts;
        }
        /// <summary>
        /// 获取存栏总数
        /// </summary>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public async Task<int>  GetHerdsCount() 
        {
            var client = _httpClientFactory.CreateClient();
            // 发送 HTTP 请求获取数据
            var response = await client.GetAsync("https://localhost:44336/api/app/growthstage/sheep-show");
            if (!response.IsSuccessStatusCode)
            {
                throw new Exception("Failed to fetch data from the API.");
            }
            // 读取响应内容并反序列化
            var jsonString = await response.Content.ReadAsStringAsync();
            var data = JsonConvert.DeserializeObject<List<YourDataModel>>(jsonString);
            var count = data.Count();
            return count;
        }
        /// <summary>
        /// 种公存栏
        /// </summary>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public async Task<List<BreedingDTO>> GetSeedmaleCount()
        {
          
            var client = _httpClientFactory.CreateClient();
            // 发送 HTTP 请求获取数据
            var response = await client.GetAsync("https://localhost:44336/api/app/growthstage/sheep-showg");

            if (!response.IsSuccessStatusCode)
            {
                throw new Exception("Failed to fetch data from the API.");
            }

            // 读取响应内容并反序列化
            var jsonString = await response.Content.ReadAsStringAsync();
            var data = JsonConvert.DeserializeObject<List<YourDataModel>>(jsonString);

            // 使用 LINQ 进行分组和计数
            var breedingCounts = data
                .GroupBy(item => item.Variety)
                .Select(group => new BreedingDTO
                {
                    SumName = group.Key,
                    SumCount = group.Count()
                })
                .ToList();

            return breedingCounts;

        }
        
        /// <summary>
        /// 配种数量统计
        /// </summary>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public async Task<int> GetBreedingCount()
        {
            var client = _httpClientFactory.CreateClient();
            // 发送 HTTP 请求获取数据
            var response = await client.GetAsync("https://localhost:44336/api/app/hybridization/hybridization-show");
            if (!response.IsSuccessStatusCode)
            {
                throw new Exception("Failed to fetch data from the API.");
            }
            // 读取响应内容并反序列化
            var jsonString = await response.Content.ReadAsStringAsync();
            var data = JsonConvert.DeserializeObject<List<YourDataModel>>(jsonString);
            var count = data.Count();
            return count;
        }
      
        /// <summary>
        /// 分娩统计数量
        /// </summary>
        /// <returns></returns>
        public async Task<int> GetParturitionCount() 
        {
            var client = _httpClientFactory.CreateClient();
            // 发送 HTTP 请求获取数据
            var response = await client.GetAsync("https://localhost:44336/api/app/seedbirth/seedbirth-show");
            if (!response.IsSuccessStatusCode)
            {
                throw new Exception("Failed to fetch data from the API.");
            }
            // 读取响应内容并反序列化
            var jsonString = await response.Content.ReadAsStringAsync();
            var data = JsonConvert.DeserializeObject<List<YourDataModel>>(jsonString);
            var count = data.Count();
            return count;
        }
        /// <summary>
        /// 统计活羊总数量
        /// </summary>
        /// <returns></returns>
        public async Task<int> GetSumLivesheep() 
        {
            var client = _httpClientFactory.CreateClient();
            // 发送 HTTP 请求获取数据
            var response = await client.GetAsync("https://localhost:44336/api/app/seedbirth/livelamber-show");
            if (!response.IsSuccessStatusCode)
            {
                throw new Exception("Failed to fetch data from the API.");
            }
            // 读取响应内容并反序列化
            var jsonString = await response.Content.ReadAsStringAsync();
            var data = JsonConvert.DeserializeObject<List<YourDataModel>>(jsonString);
            var count = data.Sum(d => d.Num);
            return count;
        }
        /// <summary>
        /// 统计死羊总数量
        /// </summary>
        /// <returns></returns>
        public async Task<int> GetSumDeadsheep()
        {
            var client = _httpClientFactory.CreateClient();
            // 发送 HTTP 请求获取数据
            var response = await client.GetAsync("https://localhost:44336/api/app/seedbirth/liffreks-show");
            if (!response.IsSuccessStatusCode)
            {
                throw new Exception("Failed to fetch data from the API.");
            }
            // 读取响应内容并反序列化
            var jsonString = await response.Content.ReadAsStringAsync();
            var data = JsonConvert.DeserializeObject<List<YourDataModel>>(jsonString);
            var count = data.Sum(d => d.Num);
            return count;
        }

        /// <summary>
        /// 统计断奶的窝数
        /// </summary>
        /// <returns></returns>
        public async Task<int> GetAblactationDeadsheep()
        {
            var client = _httpClientFactory.CreateClient();
            // 发送 HTTP 请求获取数据
            var response = await client.GetAsync("https://localhost:44336/api/app/seedweaning/wig");
            if (!response.IsSuccessStatusCode)
            {
                throw new Exception("Failed to fetch data from the API.");
            }
            // 读取响应内容并反序列化
            var jsonString = await response.Content.ReadAsStringAsync();
            var data = JsonConvert.DeserializeObject<List<YourDataModel>>(jsonString);
            var count = data.Count();
            return count;
        }

        /// <summary>
        /// 统计断奶总重
        /// </summary>
        /// <returns></returns>
        public async Task<double> GetAblactationWeight()
        {
            var client = _httpClientFactory.CreateClient();
            // 发送 HTTP 请求获取数据
            var response = await client.GetAsync("https://localhost:44336/api/app/seedweaning/wig");
            if (!response.IsSuccessStatusCode)
            {
                throw new Exception("Failed to fetch data from the API.");
            }
            // 读取响应内容并反序列化
            var jsonString = await response.Content.ReadAsStringAsync();
            var data = JsonConvert.DeserializeObject<List<YourDataModel>>(jsonString);
            var count = data.Sum(d => d.Weight);
            return count;
        }
        /// <summary>
        /// 统计断奶总重
        /// </summary>
        /// <returns></returns>
        public async Task<double> GetAvgWeight()
        {
            var client = _httpClientFactory.CreateClient();
            // 发送 HTTP 请求获取数据
            var response = await client.GetAsync("https://localhost:44336/api/app/seedweaning/wig");
            if (!response.IsSuccessStatusCode)
            {
                throw new Exception("Failed to fetch data from the API.");
            }
            // 读取响应内容并反序列化
            var jsonString = await response.Content.ReadAsStringAsync();
            var data = JsonConvert.DeserializeObject<List<YourDataModel>>(jsonString);
            var count = data.Sum(d => d.Weight);
            var Count = data.Count();
            var list = count/Count;
            return list;
        }


        /// <summary>
        /// 淘汰耳号下拉框
        /// </summary>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public async Task<List<DropdownItemDto>> GetEarbugles()
         {
           
            var client = _httpClientFactory.CreateClient();
            // 发送 HTTP 请求获取数据
            var response = await client.GetAsync("https://localhost:44336/api/app/earoverbit/earoverbits");
            if (!response.IsSuccessStatusCode)
            {
                throw new Exception("Failed to fetch data from the API.");
            }
            // 读取响应内容并反序列化
            var jsonString = await response.Content.ReadAsStringAsync();
            var data = JsonConvert.DeserializeObject<List<EarOverbit>>(jsonString);
            // 查询已使用的数据的 Id 列表
            var usedDataIds = _weighInfoRepository.GetListAsync().Result.Select(d => d.Earbugles).ToList();
            // 查询所有数据，并过滤已使用的数据
            var list = data.Where(d => !usedDataIds.Contains(d.OverbitName)).ToList();
            // 转换为 DropdownItemDto 并返回
            return list.Select(d => new DropdownItemDto { Id = d.Id, Name = d.OverbitName }).ToList();
        }


       
    }

}

